package com.fzfnn.scrapbook.service.impl;

import com.fzfnn.scrapbook.entity.Journal;
import com.fzfnn.scrapbook.entity.User;
import com.fzfnn.scrapbook.mapper.JournalMapper;
import com.fzfnn.scrapbook.mapper.UserFollowMapper;
import com.fzfnn.scrapbook.mapper.UserMapper;
import com.fzfnn.scrapbook.service.JournalCommonService;
import com.fzfnn.scrapbook.service.PicturesService;
import com.fzfnn.scrapbook.util.R;

import com.fzfnn.scrapbook.vo.JournalVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class JournalCommonSericeImpl implements JournalCommonService {
    @Autowired
    private JournalMapper journalMapper;
    @Autowired
    private UserFollowMapper userFollowMapper;
    @Autowired
    private PicturesService picturesService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate<String, String> redisMail;

    @Override
    public R getJournal() {
        List<Journal> journalList = journalMapper.getJournals();
        return R.successData(journalList);
    }

    @Override
    public R getJournalbyPublic() {
        List<JournalVo> journalList = journalMapper.getJournalsbyPublic();
        return R.successData(journalList);
    }


    @Override
    public R getJournalbyId(Integer journalId, String token) {
        String userIdStr = redisMail.opsForValue().get("token:" + token);
        if (userIdStr == null) {
            return R.errorMsg("登录信息已过期，请重新登录");
        }
        Journal journalList = journalMapper.getJournalByIdWithUserInfo(journalId);
        if (journalList== null) {
            return R.errorMsg("手账不存在或未公开");
        } else {
            return R.successData(journalList);
        }
    }

    @Override
    public R getPublicJournalsByPage(int page, int size) {
        int offset = (page - 1) * size;

        List<Journal> records = journalMapper.selectPublicJournalsByPage(offset, size);
        int total = journalMapper.countPublicJournals();
        int pages = (int) Math.ceil((double) total / size);

        Map<String, Object> data = new HashMap<>();
        data.put("records", records);
        data.put("total", total);
        data.put("pages", pages);
        data.put("current", page);

        return R.success("data", data);
    }

    @Override
    public R getJournalsFromFollowedUsers(String token) {
        String userId = redisMail.opsForValue().get("token:" + token);
        if (userId == null) {
            return R.errorMsg("登录信息无效");
        }

        List<Integer> followedIds = userFollowMapper.getFollowedIds(Integer.parseInt(userId));
        if (followedIds == null || followedIds.isEmpty()) {
            return R.successData(new ArrayList<>());
        }
        return R.successData(journalMapper.getJournalsFromFollowed(followedIds));
    }

    // 新增个性化推荐方法
    @Override
    public R getRecommendedJournalsByPage(String token, int page, int size) {
        String userIdStr = redisMail.opsForValue().get("token:" + token);
        if (userIdStr == null) {
            return R.errorMsg("登录信息无效");
        }
        int offset = (page - 1) * size;
        // 1. 先获取用户相关tag
        List<String> rawTags = journalMapper.selectTagsByUserActivity(Integer.valueOf(userIdStr));

        // 2. 转成 ArrayList 避免反射异常
        List<String> tagList = new ArrayList<>();
        for (String tagStr : rawTags) {
            if (tagStr != null && !tagStr.trim().isEmpty()) {
                String[] splitTags = tagStr.split("[,，；;\\s]+");
                for (String tag : splitTags) {
                    if (!tag.trim().isEmpty()) {
                        tagList.add(tag.trim());
                    }
                }
            }
        }

        // 3. 查询个性化推荐手账
        List<Journal> records = journalMapper.selectRecommendedPublicJournals(tagList, size, offset);
        int total = journalMapper.countRecommendedPublicJournals(tagList);
        int pages = (int) Math.ceil((double) total / size);

        Map<String, Object> data = new HashMap<>();
        data.put("records", records);
        data.put("total", total);
        data.put("pages", pages);
        data.put("current", page);

        return R.success("data", data);

    }
}
